package com.structure.algorithm;

/**
 * Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space?
 * Created by 乔磊 on 2015/12/1.
 */
public class LinkedListCycle {
    public boolean isHasCycle(ListNode head){
        //节点为空或者节点的next节点为空，直接返回false
        if(head == null || head.next ==null){
            return false;
        }
        //定义两个节点：快节点和慢节点
        ListNode fast,slow;
        //快节点的地址指向head
        fast = head;
        //慢节点的地址指向head
        slow = head;
        //如果两个节点地址不相等，则无环，否则有环
        while(fast !=null && fast.next !=null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast==slow){
                return true;
            }
        }
        return false;
    }
    public static void main(String[] args){
        ListNode head = new ListNode(1);
        head.next = new ListNode(1);
        System.out.print(new LinkedListCycle().isHasCycle(head));
    }
}
